import { useReducer } from "react";
import { Button } from "antd";

function getData(){
  return new Promise((s,r)=>{
    
    setTimeout( ()=>{
      const a = Math.random()
    alert(a)
      s(a)
    },1000)
  })
}

function UseReducerSimple() {
  console.log("=========== UseReducerSimple render =============== ")
  const [state, dispatch] = useReducer(
    async function (state, action) {
      console.log('old state',state);
      switch (action.type) {
        case "increment":
          console.log("actionType:increment");
          return { ...state, age: state.age + action.payload };
        case "decrement":
          console.log("actionType:decrement");
          return { ...state, age: state.age - action.payload };
        case "changeName":
          console.log("actionType:changeName");
          const newName = await getData();
          alert(newName)
          return { ...state, name: 'lisi' };
        default:
          return state;
      }
    },
    {
      name: "zhangsan",
      age: 5,
    }
  );

  return (
    <div>
      Name:{state.name}{" "}
      <Button onClick={()=>{dispatch({ type: "changeName" })}}>Change Name</Button>
      <br />
      age:{state.age}
      <Button onClick={()=>{dispatch({ type: "increment", payload: 2 })}}> + </Button>
      <Button onClick={()=>{dispatch({ type: "decrement", payload: 1 })}}> - </Button>
    </div>
  );
}

export default UseReducerSimple;
